package com.cogwheel.framework.graphics.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.media.opengl.GL2;

import com.cogwheel.framework.graphics.CSprite;
import com.cogwheel.framework.init.CPreferences;
import com.cogwheel.framework.util.CDebug;
import com.cogwheel.framework.util.CRectangle;

public class CFont extends CSprite{
	private char[] symbols = {};
	private int[]  positions;
	public float CharScale, CharSpace;
	private String text = "";
	
	public CFont(CPreferences preferences, String spriteID, String descriptorPlace, String text, CRectangle dimensions){
		this(preferences, spriteID, descriptorPlace, text, dimensions, 1f, 1f);
	}
	public CFont(CPreferences preferences, String spriteID, String descriptorPlace, String text, CRectangle dimensions, float charScale, float charSpace) {
		super(preferences, spriteID, dimensions);
		
		CharScale = charScale; CharSpace = charSpace;
		CWGReadDescriptor(descriptorPlace);
		CWGCalcNewText(text);
	}
	
	public void CWGSetText(String text){ CWGCalcNewText(text); }
	public String CWGGetText(){ return text; }
	public int CWGGetSymbolCount(){ return symbols.length; }
	
	private void CWGReadDescriptor(String file){
		try{
			BufferedReader bReader = new BufferedReader(new FileReader(new File(file)));
			symbols = bReader.readLine().toCharArray();
			bReader.close();
		}catch (IOException e){ CDebug.error("CFont", "Could not read font descriptor file!"); }
	}
	
	private void CWGCalcNewText(String text){
		positions = new int[text.length()];
		for (int c = 0; c < positions.length; c++){
			for(int a = 0; a < symbols.length; a++){
				if (text.charAt(c) == symbols[a]){ positions[c] = a; break; }
			}
		}
		
		this.text = text;
	}
	
	@Override
	public void CDraw2D(GL2 gl){
		if (TextureID != "NULL" && TextureID != null){	
			gl.glTranslatef(xa, ya, 1f);
			//gl.glRotatef(Rotation, 0.0f, 0f, 1f);
			
			for (int c = 0; c < positions.length; c++){
				gl.glBegin(GL2.GL_QUADS);
					gl.glTexCoord2f(positions[c] * (1f / symbols.length), 1.0f); //Upper left
					gl.glVertex2f((-w/symbols.length)*CharScale, h*CharScale);
		
					gl.glTexCoord2f((positions[c] + 1 )* (1f / symbols.length), 1.0f); //Upper right
					gl.glVertex2f((w/symbols.length)*CharScale, h*CharScale);
		
					gl.glTexCoord2f((positions[c] + 1) * (1f / symbols.length), 0.0f); //Bottom right
					gl.glVertex2f((w/symbols.length)*CharScale, -h*CharScale);
		
					gl.glTexCoord2f(positions[c] * (1f / symbols.length), 0.0f); //Bottom left
					gl.glVertex2f((-w/symbols.length)*CharScale, -h*CharScale);
				gl.glEnd();
				gl.glTranslatef((w/symbols.length) * CharScale / CharSpace, 0f, 0f);
			}
		}
	}
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
